#include "export.h"
#include "config.h"

#ifdef HAVE_LIBPNG
#  include "png.h"
#endif

#include "imageset.h"

int image_export_png(Image* img, char* filename)
{
#ifndef HAVE_LIBPNG
	fprintf(stderr, "libpng library is not installed.\n");
	return 0;
#else
	// initialize
	png_structp png_ptr;
	png_infop info_ptr;

	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
			NULL, NULL, NULL);
	if(!png_ptr)
		return 0;

	info_ptr = png_create_info_struct(png_ptr);
	if(!info_ptr)
	{
		png_destroy_write_struct(&png_ptr, NULL);
		return 0;
	}

	// error management
	if(setjmp(png_ptr->jmpbuf))
	{
		png_destroy_write_struct(&png_ptr, &info_ptr);
		return 0;
	}

	// open file
	FILE* f = fopen(filename, "wb");
	if(!f)
		return 0;
	png_init_io(png_ptr, f);
	png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);

	// setup image
	png_set_IHDR(png_ptr, info_ptr, img->w, img->h, 8,
			PNG_COLOR_TYPE_RGB | PNG_COLOR_MASK_PALETTE,
			PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
			PNG_FILTER_TYPE_DEFAULT);

	// setup palette
	png_color plte[256];
	int i;
	for(i=0; i<256; i++)
	{
		Imageset* is = (Imageset*)img->is;
		plte[i].red   = is->color[i].r;
		plte[i].green = is->color[i].g;
		plte[i].blue  = is->color[i].b;
	}
	png_set_PLTE(png_ptr, info_ptr, plte, 256);

	// transparency
	png_byte trans[256];
	for(i=0; i<255; i++)
		trans[i] = 255;
	trans[255] = 0;
	png_set_tRNS(png_ptr, info_ptr, trans, 256, NULL);

	png_write_info(png_ptr, info_ptr);

	// write data
	for(i=0; i<img->h; i++)
		png_write_row(png_ptr, &img->data[img->w * i]);

	// finish writing
	png_write_end(png_ptr, NULL);
	fclose(f);

	// cleanup
	png_destroy_write_struct(&png_ptr, &info_ptr);

	return 1;
#endif
}
